//
//  XFComposeViewController.m
//  Weibo
//
//  Created by Fay on 15/10/9.
//  Copyright (c) 2015年 Fay. All rights reserved.
//

#import "XFComposeViewController.h"
#import "XFTextView.h"
#import "AFNetworking.h"
#import "XFComposeToolbar.h"
#import "XFComposePhotosView.h"
#import "XFEmotionKeyboard.h"
#import "XFEmotion.h"
#import "XFEmotionTextView.h"
#import "MHComposeViewModel.h"
#import "MHPhotoManager.h"
#import "MHTagsTableView.h"
#import "MHAlertTextFeildView.h"
#import "MHCircleAllTags.h"
#import "MHCircleUserTag.h"
#import "MHStatusComposeTextParser.h"
#import <YYText/YYText.h>
#import "UITextView+MHExtension.h"
#import "MHUploadImage.h"
#import "YYTextView+MHExtension.h"
#import "MHLocationIndicateView.h"
#import "MHLocationViewModel.h"
#import "MHLocationManager.h"
#import "MHLocationTipsView.h"


@interface XFComposeViewController ()<UITextViewDelegate,XFComposeToolbarDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,IDMPhotoBrowserDelegate,YYTextKeyboardObserver,UIGestureRecognizerDelegate,YYTextViewDelegate,MHLocationManagerAppdelegate>
/** 输入控件 */
@property (nonatomic, weak) XFEmotionTextView *textView;
/** 键盘顶部的工具条 */
@property (nonatomic, weak) XFComposeToolbar *toolbar;
/** 相册（存放拍照或者相册中选择的图片） */
@property (nonatomic,weak)XFComposePhotosView *photoView;
/** 表情键盘 */
@property (nonatomic, strong) XFEmotionKeyboard *emotionKeyboard;

@property(nonatomic, strong) MHTagsTableView *tagTableView;

@property(nonatomic, strong)  MHComposeViewModel *viewModel;
@property(nonatomic, assign) CGRect orginalFrame;
/** 是否正在切换键盘 */
@property (nonatomic, assign) BOOL switchingKeybaord;

@property(nonatomic, strong) MHCircleAllTags *allTags;

@property(nonatomic, strong) NSMutableArray  *selectAssert;

@property(nonatomic, strong) NSMutableArray *selectUploadModels;
@property(nonatomic, strong) MHLocationIndicateView *locationIndicateView;

@end

@implementation XFComposeViewController
@dynamic viewModel;

#define kMaxValue 5000


- (XFEmotionKeyboard *)emotionKeyboard
{
    if (!_emotionKeyboard) {
        self.emotionKeyboard = [[XFEmotionKeyboard alloc] init];
        self.emotionKeyboard.width = self.view.width;
        self.emotionKeyboard.height = 256;
        __weak __typeof(self)weakSelf = self;
        self.emotionKeyboard.sendBlock = ^{
            [weakSelf sendWithImage];
        };
    }
    return _emotionKeyboard;
    
}


-(MHTagsTableView *)tagTableView
{
    if (!_tagTableView) {
         MHTagsTableView *tagsTableView = [[MHTagsTableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tagTableView = [tagsTableView initWithData:@[@[@[]],@[]]];
        _tagTableView.width = self.view.width;
        WEAKSELF
        _tagTableView.removeTagBlock = ^(int tagId) {
            [[weakSelf.viewModel.removeUserTagCommand execute:@(tagId)] subscribeNext:^(id x) {
                NSString *tagStr = [NSString stringWithFormat:@"autoId == %d",tagId];
                [ weakSelf.allTags.userTags removeObjectsInArray:[ weakSelf.allTags.userTags filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:tagStr]]];
                [weakSelf configTagDataWith:weakSelf.allTags];
            }];
        };
        
        _tagTableView.selectCellBlock = ^(MHCircleUserTag *tag) {
            [weakSelf.textView insertTags:tag];
        };
        _tagTableView.tapCircleTagBlock = ^(MHCircleUserTag *tag) {
            [weakSelf.textView insertTags:tag];
        };
        _tagTableView.addTagBlock = ^{
            MHAlertTextFeildView *textFeildView =[MHAlertTextFeildView mh_viewFromXib];
            textFeildView.mh_width = self.view.mh_width * 0.8;
            weakSelf.textView.inputView = nil;
            [weakSelf.textView resignFirstResponder];
            [textFeildView.cancelBtn bk_whenTapped:^{
                [weakSelf.zh_popupController dismiss];
            }];
            [textFeildView.sendBtn bk_whenTapped:^{
                if (textFeildView.addTagTextFeild.text.length <= 0) {
                    [MBProgressHUD mh_showTips:@"请输入标签名字！"];
                    return;
                }
                
                if (textFeildView.addTagTextFeild.text.length > 15) {
                    [MBProgressHUD mh_showTips:@"最多可输入15个字!"];
                    return;
                }
                [[weakSelf.viewModel.addUserTagCommand execute:textFeildView.addTagTextFeild.text] subscribeNext:^(MHHTTPResponse *respose) {
                    if (!respose.parsedResult) {
                        return ;
                    }
                    MHCircleUserTag *tag = [MHCircleUserTag new];

                    tag.autoId = [respose.parsedResult[@"tagId"] integerValue];
                    tag.tagName = textFeildView.addTagTextFeild.text;
                    [weakSelf.allTags.userTags prependObject:tag];
                    [weakSelf configTagDataWith:weakSelf.allTags];
                }];
                [weakSelf.zh_popupController dismiss];
            }];
            weakSelf.zh_popupController = [zhPopupController new];
            [weakSelf.zh_popupController presentContentView:textFeildView];
        };
        _tagTableView.height = 256;
    }
    return _tagTableView;
}


/**
 定位标签

 @return 定位标签
 */
-(MHLocationIndicateView *)locationIndicateView
{
    if (!_locationIndicateView) {
     
        _locationIndicateView = [MHLocationIndicateView mh_viewFromXib];
        __weak __typeof(self)weakSelf = self;
        [_locationIndicateView bk_whenTapped:^{
            if (![MHLocationManager isLocationServiceOpen]) {
                MHLocationTipsView *locationView = [MHLocationTipsView mh_viewFromXib];
                weakSelf.zh_popupController = [zhPopupController new];
                //        self.zh_popupController.layoutType = zhPopupLayoutTypeBottom;
                locationView.width = self.view.mh_width * 0.7;
                locationView.layer.cornerRadius = 8.0;
                locationView.masksToBounds = YES;
                [self.zh_popupController presentContentView:locationView];
                //        locationView.settingButton.rac_command = self.viewModel.nextCommand;
                __weak __typeof(self)weakSelf = self;
                [locationView.startLocation bk_whenTapped:^{
                    [[MHLocationManager sharedInstance] openLocationSetting];
                    [weakSelf.zh_popupController dismiss];
                }];
                [weakSelf.textView resignFirstResponder];
                [locationView.dissBtn bk_whenTapped:^{
                    
                    [weakSelf.zh_popupController dismiss];
                }];
            }else
            {
                MHLocationViewModel *locationModel = [[MHLocationViewModel alloc] initWithServices:self.viewModel.services params:self.viewModel.model.location ? @{MHViewModelUtilKey:self.viewModel.model.location} : nil ];
                locationModel.isRecentLocation = YES;
                [self.viewModel.services pushViewModel:locationModel animated:YES];
                locationModel.completeBlock = ^(MHCustomTip *tip) {
                    
                    weakSelf.locationIndicateView.locationLabel.text = !tip.isShowLocation ? @"不显示位置" : tip.name;
                    if (tip.isShowLocation) {
                        weakSelf.viewModel.circleLocation = tip.circleLocation;
                    }else
                    {
                        weakSelf.viewModel.circleLocation = tip.circleLocation;
                    }
                };
            }
           
        }];
    }
    return _locationIndicateView;
}

- (NSMutableArray *)selectedAlbumPhotosIncludingGifWithPHAssets:(NSArray*)assets photos:(NSArray *) photos{
    
   __block NSMutableArray *imageArray = [NSMutableArray array];
    PHImageRequestOptions *options = [PHImageRequestOptions new];
    options.resizeMode = PHImageRequestOptionsResizeModeFast;
    options.synchronous = YES;
    
    PHCachingImageManager *imageManager = [[PHCachingImageManager alloc] init];
    for (PHAsset *asset in assets) {
        
        [imageManager requestImageDataForAsset:asset
                                       options:options
                                 resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
                                     
//                                     DDLogDebug(@"dataUTI:%@",dataUTI);
                                     
                                     //gif 图片
                                     if ([dataUTI isEqualToString:(__bridge NSString *)kUTTypeGIF]) {
                                         BOOL downloadFinined = (![[info objectForKey:PHImageCancelledKey] boolValue] && ![info objectForKey:PHImageErrorKey]);
                                         if (downloadFinined && imageData) {
                                             MHUploadImage *pic = [MHUploadImage new];
                                             pic.image = [UIImage imageWithData:imageData];
                                             pic.orginalData = imageData;
                                             pic.isGif = YES;
//                                             UIImage *gifImage =  [UIImage imageWithData:imageData];
                                             [imageArray addObject:pic];
                                         }
                                     }
                                     else {
                                         
                                         MHUploadImage *pic = [MHUploadImage new];
                                         int index = [assets indexOfObject:asset];
                                         pic.image =  photos[index];
//                                         pic.orginalData = imageData;
                                         pic.isGif = NO;
//
                                         [imageArray addObject:pic];
                                     }
                                     
                                 }];
        
    }
    
    return imageArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    //设置导航栏内容
    [self setupNav];
    //设置输入框
    [self setupInput];
    //设置工具条
        [self setupToolbar];
   //添加图片
    [self setupPhotoView];
    [self.view addSubview:self.locationIndicateView];
    [self startLacation];
    [self.locationIndicateView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.height.equalTo(@44);
        make.bottom.equalTo(self.photoView.mas_top);
    }];

    [[YYTextKeyboardManager defaultManager] addObserver:self];
    @weakify(self);
    [[self.viewModel.fetchTagsCommand execute:nil] subscribeNext:^(MHCircleAllTags *allTags) {
        @strongify(self);
        self.allTags = allTags;
        [self configTagDataWith:allTags];
    }];
}

-(void) startLacation
{
    __weak __typeof(self)weakSelf = self;
    [[MHLocationManager sharedInstance] startUpdatingLocationWithBlock:^(CLLocation *location){
        [[MHLocationManager sharedInstance] searhAroundWithLocation:location reslutBlock:^(AMapPOISearchBaseRequest *requst,AMapPOISearchResponse *response) {
            if (response.pois.count > 0) {
                AMapPOI *currentPOI =  response.pois.firstObject;
                MHCustomTip *tip =  [MHCustomTip createWithAMapPOI:currentPOI];
                weakSelf.viewModel.circleLocation = tip.circleLocation;
                weakSelf.locationIndicateView.locationLabel.text = currentPOI.name;
            }
        }];
        [MHLocationManager uploadLocationToRemote:location];
    }];
    
    [MHLocationManager sharedInstance].delegate = self;
    
    if (![MHLocationManager isLocationServiceOpen]) {
         [self configCirclePositon];
    }
}

-(void) configCirclePositon
{
    if (self.viewModel.model.location ) {
        self.viewModel.circleLocation = self.viewModel.model.location;
        self.locationIndicateView.locationLabel.text = self.viewModel.model.location.isShowLocation ? self.viewModel.model.location.areaName : @"不显示位置";
    }
}

-(void)mhmapLocationManager:(AMapLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    if (status == kCLAuthorizationStatusDenied ||status ==  kCLAuthorizationStatusRestricted) {
        [self configCirclePositon];
    }
}

-(void) configTagDataWith:(MHCircleAllTags *)allTags{
    if ([self.viewModel.model currentUserIsOwner]) {
        self.tagTableView.tagsData = @[allTags.userTags];
    }else
    {
        self.tagTableView.tagsData = @[allTags.circleTags,allTags.userTags];
    }
}



-(void)deletePhotoAtIndex:(NSUInteger)index
{
    [self.photoView.photos removeObjectAtIndex:index];
    [self.photoView.imageCollection reloadData];
}


-(void)bindViewModel
{
    [super bindViewModel];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[YYTextKeyboardManager defaultManager] removeObserver:self];
}

-(void) dissMiss
{
    [self.viewModel.closeCommand execute:nil];
}

//设置导航栏内容
-(void)setupNav {
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem mh_customItemWithTitle:@"取消" titleColor:nil imageName:nil target:self selector:@selector(dissMiss) contentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];;
    self.navigationItem.rightBarButtonItem =   [UIBarButtonItem mh_customItemWithTitle:@"发送" titleColor:nil imageName:nil target:self selector:@selector(send) contentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
    NSString *circleName = self.viewModel.model.title;
    NSString *prefix = @"发送至";
    
    if (circleName) {
        UILabel *titleView = [[UILabel alloc]init];
        titleView.height = 100;
        titleView.width = 200;
        titleView.numberOfLines = 0;
        titleView.textAlignment = NSTextAlignmentCenter;
        titleView.y = 50;
        NSString *str = [NSString stringWithFormat:@"%@\n%@", prefix, circleName];
        // 创建一个带有属性的字符串（比如颜色属性、字体属性等文字属性）
        NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc]initWithString:str];
        [attStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:[str rangeOfString:prefix]];
        [attStr addAttribute:NSForegroundColorAttributeName value:MHTextColor333 range:[str rangeOfString:prefix]];
        [attStr addAttribute:NSFontAttributeName value:MHRegularFont_12 range:[str rangeOfString:circleName]];
        [attStr addAttribute:NSForegroundColorAttributeName value:MHTextColorF75 range:[str rangeOfString:circleName]];
        titleView.attributedText = attStr;
        self.navigationItem.titleView = titleView;
    }else{
        self.title = prefix;
    }
    
    
}

//添加工具条
-(void)setupToolbar {
    
    XFComposeToolbar *toolbar = [[XFComposeToolbar alloc] initWithType:self.viewModel.type frame:CGRectZero];
    toolbar.height = 44;
    toolbar.x = 0;
    toolbar.y = self.view.height - toolbar.height;
    toolbar.width = self.view.width;
    toolbar.delegate = self;
    [self.view addSubview:toolbar];
    self.toolbar = toolbar;
    
}


//设置输入框
-(void)setupInput {
    
    XFEmotionTextView *textView = [[XFEmotionTextView alloc]init];
    textView.frame = self.view.frame;
    textView.font = [UIFont systemFontOfSize:16];
    [self.view addSubview:textView];
    textView.delegate = self;
    textView.placeholderText  = @"说点什么吧...";
    self.textView = textView;
    textView.allowsCopyAttributedString = NO;
    textView.inputAccessoryView = [UIView new];
    textView.textParser = [MHStatusComposeTextParser new];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(textViewTapped:)];
    tap.delegate = self;
    // 监听通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:textView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(emotionDidSelect:) name:@"EmotionDidSelectNotification" object:nil];
    //键盘删除的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteBtn) name:@"EmotionDidDeleteNotification" object:nil];
}



-(void)viewWillLayoutSubviews
{
    
    [super viewWillLayoutSubviews];
//    self.photoView.mh_bottom = self.toolbar.mh_top;
}


- (BOOL)textView:(YYTextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if (self.viewModel.type == MHCirclComposeTypeVideo) {
        return [textView textView:textView shouldChangeTextInRange:range replacementText:text maxLength:55];
    }else
    {
        return YES;
    }
}

- (void)textViewDidChange:(YYTextView *)textView {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSString *toBeString = textView.text;
        UITextRange *selectedRange = [textView markedTextRange];//获取高亮部分
        UITextPosition *position = [textView positionFromPosition:selectedRange.start offset:0];
        if (!position) { // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
            if (toBeString.length > kMaxValue) {
                NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:kMaxValue];
                if (rangeIndex.length == 1) {
                    textView.text = [toBeString substringToIndex:kMaxValue];
                } else {
                    NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, kMaxValue)];
                    textView.text = [toBeString substringWithRange:rangeRange];
                }
            }
        }
    });
}

- (void)textViewTapped:(UITapGestureRecognizer *)tap {
    self.textView.inputView = nil;
    [self.textView reloadInputViews];
    [self.textView becomeFirstResponder];
}

#pragma mark - Gesture recognizer delegate

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}


- (void)keyboardChangedWithTransition:(YYTextKeyboardTransition)transition {
    CGRect toFrame = [[YYTextKeyboardManager defaultManager] convertRect:transition.toFrame toView:self.view];
    self.orginalFrame = toFrame;
    if (transition.animationDuration == 0) {
        _toolbar.bottom = CGRectGetMinY(toFrame);
    } else {
        __weak __typeof(self)weakSelf = self;
        [UIView animateWithDuration:transition.animationDuration delay:0 options:transition.animationOption | UIViewAnimationOptionBeginFromCurrentState animations:^{
            weakSelf.toolbar.bottom = CGRectGetMinY(toFrame);
        } completion:NULL];
    }
    NSLog(@"mh_bottom == %.0f",self.toolbar.mh_top);
     self.photoView.mh_bottom = self.toolbar.mh_top;//{0, 190.5}, {320, 80}
    [self chageContenInset];
    
    
}

-(void) chageContenInset
{
    if (self.photoView.photos.count > 0) {
        if (@available(iOS 11, *)) {
            self.textView.contentInset = UIEdgeInsetsMake(0, 0, self.view.height - self.photoView.mh_top + 44 + self.textView.mh_y, 0);
        }else
        {
            self.textView.contentInset = UIEdgeInsetsMake(isIPhoneX()? 100 :76, 0, self.view.height - self.photoView.mh_top +  44 + self.textView.mh_y , 0);
        }
        
        
    }else
    {
        if (@available(iOS 11, *)) {
            self.textView.contentInset = UIEdgeInsetsMake(0, 0, self.view.height - self.photoView.mh_top + 44 + self.textView.mh_y, 0);
        }else
        {
            self.textView.contentInset = UIEdgeInsetsMake(isIPhoneX()? 100 :76, 0, self.view.height - self.toolbar.mh_top, 0);
        }
    }
}

-(void) addPhotoImage:(MHUploadImage *)image
{
    [self.photoView addPhoto:image];
    self.photoView.height = 80;
    [self.photoView layoutIfNeeded];
    self.photoView.mh_bottom = self.toolbar.mh_top;
    [self chageContenInset];
}

//添加相册
-(void)setupPhotoView {
    
    XFComposePhotosView *photoView = [[XFComposePhotosView alloc]initWithFrame:CGRectZero];
    photoView.width = self.view.width;
    photoView.mh_bottom = self.toolbar.mh_top;
    [self.view addSubview:photoView];
    self.photoView = photoView;
    __weak __typeof(self)weakSelf = self;
    
    
    if (self.viewModel.type == MHCirclComposeTypeVideo) {
        MHUploadImage *pic = [MHUploadImage new];
        pic.image = self.viewModel.videoCoverImage;
        pic.isGif = NO;
        pic.isVideoCover = YES;
        [self addPhotoImage:pic];
    }else
    {
        self.photoView.selectImageBlock = ^(int index) {
            NSMutableArray *photoArrary = [NSMutableArray array];
            for (MHUploadImage *image in self.photoView.photos) {
                [photoArrary addObject:image.image];
            }
            [MHPhotoManager previewPhotos:self maxImagesCount:(self.viewModel.type == MHCirclComposeTypePublish)?9:1 selectedAssets:self.selectAssert selectedPhotos:photoArrary currentIndex:index completion:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto, NSArray<NSDictionary *> *infos) {
                [weakSelf.photoView.photos removeAllObjects];
                NSMutableArray *photesArray =  [self selectedAlbumPhotosIncludingGifWithPHAssets:assets photos:photos];
                 self.selectUploadModels = photesArray;
                for (MHUploadImage *selectImage in photesArray) {
                    self.selectAssert = assets.mutableCopy;
                    if (self.photoView.photos.count < ((self.viewModel.type == MHCirclComposeTypePublish)?9:1)) {
                        [weakSelf addPhotoImage:selectImage];
                    }else
                    {
                        [MBProgressHUD mh_showTips:self.viewModel.type == MHCirclComposeTypePublish ? @"最多选择九张图片":@"最多选择一张图片"];
                    }
                }
                [self.photoView.imageCollection reloadData];
            } cancel:^{
                
            }];
        };
    }
}



#pragma mark - 监听方法
/**
 *  表情被选中了
 */
- (void)emotionDidSelect:(NSNotification *)notification
{
    XFEmotion *emotion = notification.userInfo[@"SelectEmotionKey"];
    [self.textView insertEmotion:emotion];
    
}



/**
 *  键盘删除按钮
 */
-(void)deleteBtn {
    
    [self.textView deleteBackward];
    
}


#pragma mark - UITextViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

#pragma mark - XFComposeToolbarDelegate

-(void)composeToolbar:(XFComposeToolbar *)toolbar didClickButton:(XFComposeToolbarButtonType)buttonType {
    
    
    switch (buttonType) {
        case XFComposeToolbarButtonTypeCamera: // 拍照
            if (self.photoView.photos.count >= 9) {
                [MBProgressHUD mh_showTips:@"最多选择九张图片"];
                return;
            }
            [self openCamera];
            break;
            
        case XFComposeToolbarButtonTypePicture: // 文件，上传文件
            [self openAlbum];
            break;
            
        case XFComposeToolbarButtonTypeMention: // 标签
             [self switchkeyBoardWith:XFComposeToolbarButtonTypeMention];

            break;
            
        case XFComposeToolbarButtonTypeTrend: // 没有这个操作

            break;
            
        case XFComposeToolbarButtonTypeEmotion: // 表情\键盘
            
            [self switchkeyBoardWith:XFComposeToolbarButtonTypeEmotion];
            break;
        case XFComposeToolbarButtonTypeAnonymity: // 匿名发表操作
           
            self.viewModel.isAnonyMity = toolbar.isAnonyMity;
            break;
    }
    
    
}

//切换键盘
-(void)switchkeyBoardWith:(XFComposeToolbarButtonType ) type {
    
    if (type == XFComposeToolbarButtonTypeEmotion )
    {
        if (self.textView.inputView == nil || self.textView.inputView != self.emotionKeyboard) {
            self.textView.inputView = self.emotionKeyboard;
            // 显示键盘按钮
            self.toolbar.showKeyboardButton = YES;
            
        }else {
            self.textView.inputView = nil;
            // 显示表情按钮
            self.toolbar.showKeyboardButton = NO;
            
        }
        // 开始切换键盘
        self.switchingKeybaord = YES;
        
        // 退出键盘
        [self.textView endEditing:YES];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            //弹出键盘
            [self.textView becomeFirstResponder];
            
            // 结束切换键盘
            self.switchingKeybaord = NO;
        });
    }else if(type == XFComposeToolbarButtonTypeMention)
    {
        if (self.textView.inputView == nil || self.textView.inputView != self.tagTableView) {
            self.textView.inputView = self.tagTableView;
            // 显示键盘按钮
//            self.toolbar.showKeyboardButton = YES;
            
        }else {
            self.textView.inputView = nil;
            // 显示表情按钮
//            self.toolbar.showKeyboardButton = NO;
            
        }
        // 开始切换键盘
        self.switchingKeybaord = YES;
        
        // 退出键盘
        [self.textView endEditing:YES];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            //弹出键盘
            [self.textView becomeFirstResponder];
            
            // 结束切换键盘
            self.switchingKeybaord = NO;
        });
    }
}

#pragma mark - 其他方法


-(void)openCamera {
    
    __weak __typeof(self)weakSelf = self;

    [MHPhotoManager fetchPhotosFromAlbum:self maxImagesCount:(self.viewModel.type == MHCirclComposeTypePublish)?9:1 allowCrop:NO selectedAssets:self.selectAssert completion:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto, NSArray<NSDictionary *> *infos) {
        [weakSelf.photoView.photos removeAllObjects];
        
        NSMutableArray *photesArray =  [self selectedAlbumPhotosIncludingGifWithPHAssets:assets photos:photos];
        self.selectUploadModels = photesArray;
        for (MHUploadImage *selectImage in photesArray) {
            self.selectAssert = assets.mutableCopy;
            if (self.photoView.photos.count < ((self.viewModel.type == MHCirclComposeTypePublish)?9:1)) {
                [weakSelf addPhotoImage:selectImage];
            }else
            {
                [MBProgressHUD mh_showTips:self.viewModel.type == MHCirclComposeTypePublish ? @"最多选择九张图片":@"最多选择一张图片"];
            }
            
        }
        [self.photoView.imageCollection reloadData];
        
    } cancel:^{
        
    }];
    
}


//-(BOOL)isAssetCanSelect:(PHAsset *)asset
//{
//    PHAsset *phAsset = asset;
//    switch (phAsset.mediaType) {
//        case PHAssetMediaTypeVideo: {
//            // 视频时长
//            // NSTimeInterval duration = phAsset.duration;
//            return NO;
//        } break;
//        case PHAssetMediaTypeImage: {
//            __block float imageSize;
//            PHImageRequestOptions * options = [[PHImageRequestOptions alloc] init];
//            options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
//            options.resizeMode = PHImageRequestOptionsResizeModeExact;
//            options.synchronous = YES;
//            [[PHImageManager defaultManager]
//             requestImageDataForAsset:asset
//             options:options
//             resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
//                 imageSize = imageData.length; //convert to Megabytes
//                 imageSize = imageSize/(1024*1024.0);
////                 NSLog(@"%f",imageSize);
//             }];
//            return imageSize <= 5;
//            
//        } break;
//        case PHAssetMediaTypeAudio:
//            return NO;
//            break;
//        case PHAssetMediaTypeUnknown:
//            return NO;
//            break;
//        default: break;
//    }
//    
//    return true;
//}

-(void)openAlbum {
    
    
    [self openImagePickerController:UIImagePickerControllerSourceTypePhotoLibrary];
    
}


- (void)openImagePickerController:(UIImagePickerControllerSourceType)type {
    
    if (![UIImagePickerController isSourceTypeAvailable:type]) return;
    
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.sourceType = type;
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:nil];
    
}




#pragma mark - UIImagePickerControllerDelegate
/**
 * 从UIImagePickerController选择完图片后就调用（拍照完毕或者选择相册图片完毕）
 */
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    MHUploadImage *pic = [MHUploadImage new];
    pic.image = info[UIImagePickerControllerOriginalImage];
    pic.isGif = NO;
    [self addPhotoImage:pic];
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
    
}





-(void)textDidChange {
    
    self.navigationItem.rightBarButtonItem.enabled = self.textView.hasText;
    
}


-(void)cancel {
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}


/**
 * 发布带有图片的动态
 */
- (void)sendWithImage
{
    [self.textView resignFirstResponder];
    if (self.textView.fullText.length > 55 && self.viewModel.type == MHCirclComposeTypeVideo) {
        [UIWindow showTips:@"最多不超过55个字"];
        return;
    }
    
   
    
    self.navigationItem.rightBarButtonItem.enabled = NO;
    self.viewModel.content = self.textView.fullText;
    [[self.viewModel.uploadCommand execute:self.selectUploadModels] subscribeNext:^(id x) {

    } error:^(NSError *error) {

    } completed:^{

    }];
    
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.textView.inputView = nil;
    [self.textView becomeFirstResponder];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    dispatch_async(dispatch_get_main_queue(), ^{
        [self.textView resignFirstResponder];
    });
    
}

//发动态/提问
-(void)send {
    
    if (self.textView.text.length <= 0) {
        [MBProgressHUD mh_showTips:@"请输入内容"];
        return;
    }
    if (self.photoView.photos.count <= 0    ) {
        [UIWindow showTips:@"请选择一张照片图片或照片"];
        return;
    }
     [self sendWithImage];
 
    
}
@end
